package org.dfzt.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
/**
 * 单数据源配置（jeecg.datasource.open = false时生效）
 * @Author zhoujf
 *
 */
@Configuration
@MapperScan(value={"org.dfzt.**.mapper*","com.dfzt.**.mapper*"})
public class MybatisPlusConfig {
	public static ThreadLocal<String> myTableName = new ThreadLocal<>();
	@Value("${mybatis-plus.dynamictable:#{null}}")
	private String tables;

    /**
         *  分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        // 设置sql的limit为无限制，默认是500
		PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		paginationInterceptor.setLimit(-1);
		if (tables != null && !tables.isEmpty()) {
			List<String> tableList = Arrays.asList(tables.split(","));
			List<ISqlParser> sqlParserList = new ArrayList<>();
			DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
			Map<String, ITableNameHandler> tableNameHandlerMap = new HashMap<>();
			tableList.stream().forEach(table -> {
				tableNameHandlerMap.put(table, new ITableNameHandler() {
					@Override
					public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
						return myTableName.get();// 返回null不会替换 注意 多租户过滤会将它一块过滤不会替换@SqlParser(filter=true) 可不会替换
    }
				});
			});
			dynamicTableNameParser.setTableNameHandlerMap(tableNameHandlerMap);
			sqlParserList.add(dynamicTableNameParser);
			paginationInterceptor.setSqlParserList(sqlParserList);
//    public PerformanceInterceptor performanceInterceptor() {
//        return new PerformanceInterceptor();
		}
		return paginationInterceptor;
	}
   
}
